﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GemTowerDefence.Towers
{
  public class Emerald : Tower
  {
    // Defines how fast an enemy will move when hit.
    private readonly float _speedModifier;
    // Defines how long this effect will last.
    private readonly float _modifierDuration;

    public Emerald(Texture2D texture, Texture2D bulletTexture, Vector2 position)
      : base(texture, bulletTexture, position)
    {
      Damage = 5; // Set the damage
      Range = 120; // Set the radius

      _speedModifier = 0.6f;
      _modifierDuration = 2.0f;
    }

    public override void Update(GameTime gameTime)
    {
      base.Update(gameTime);

      if (MissileTimer >= 0.75f && HasTarget)
      {
        var bullet = new Missile(MissileTexture, Vector2.Subtract(Center,
            new Vector2(MissileTexture.Width / 2F)), Rotation, 6, Damage);

        Missiles.Add(bullet);
        MissileTimer = 0;
      }

      for (var i = 0; i < Missiles.Count; i++)
      {
        var bullet = Missiles[i];

        bullet.SetRotation(Rotation);
        bullet.Update(gameTime);

        if (!IsInRange(bullet.Center))
          bullet.Kill();

        // If the bullet hits a target,
        if (HasTarget && Vector2.Distance(bullet.Center, Target.Center) < 12)
        {
          // destroy the bullet and hurt the target.
          Target.CurrentHealth -= bullet.Damage;
          bullet.Kill();

          // Apply our speed modifier if it is better than
          // the one currently affecting the target :
          if (Target.SpeedModifier <= _speedModifier)
          {
            Target.SpeedModifier = _speedModifier;
            Target.ModifierDuration = _modifierDuration;
          }
        }

        if (bullet.IsDead())
        {
          Missiles.Remove(bullet);
          i--;
        }
      }
    }
  }
}
